package cn.kjcoder.springcloud.controller;

import cn.kjcoder.springcloud.domain.JsonResult;
import cn.kjcoder.springcloud.domain.Payment;
import cn.kjcoder.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author hkj
 * @email 1349091387@qq.com
 * @date 2021/12/20
 * 源码允许修改，并且本人十分乐意有 大佬 来对代码进行 随 意 调 教
 **/
@RestController
@RequestMapping("payment")
@Slf4j
public class PaymentController {

    @Autowired
    private PaymentService paymentService;
    @Value("${server.port}")
    private String port;
    @Autowired
    private DiscoveryClient discoveryClient;

    @PostMapping("/save")
    public JsonResult save(@RequestBody Payment payment){
        int rs = paymentService.save(payment);
        log.info("插入结果：" + rs);
        if(rs > 0){
            return JsonResult.success("插入数据库成功。port:" + port);
        }else{
            return JsonResult.error(444,"插入数据库失败",null);
        }
    }

    @GetMapping("/get/{id}")
    public JsonResult<Payment> get(@PathVariable("id")Long id){
        Payment paymentById = paymentService.getPaymentById(id);
        log.info("查询结果：" + paymentById + "O(∩_∩)O哈哈~");
        if(paymentById != null){
            return JsonResult.success(paymentById + "查询数据库成功。port:" + port);
        }else{
            return JsonResult.error(444,"查询数据库失败",null);
        }
    }

    @GetMapping("/discovery")
    public Object discoveryClient(){

        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("*************ele" + service);//cloud-payment-service  cloud-order-service
        }

        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info(instance.getServiceId() + "\t" + instance.getHost() + "\t" + instance.getPort() + "\t" + instance.getUri());
        }
        //CLOUD-PAYMENT-SERVICE	192.168.183.1	8001	http://192.168.183.1:8001
        //CLOUD-PAYMENT-SERVICE	192.168.183.1	8002	http://192.168.183.1:8002
        return this.discoveryClient;
    }

    @GetMapping("/lb")
    public String lb(){
        return port;
    }

    @GetMapping("/feign/timeout")
    public String timeout(){
        try { TimeUnit.SECONDS.sleep(3); }catch (Exception e) {e.printStackTrace();}
        return port;
    }

    /*************************************链路追踪***********************************************/
    @GetMapping("/zipkin")
    public String zipkin(){
        return "hi ,i'am paymentzipkin server fall back，welcome to my world，O(∩_∩)O哈哈~";
    }


}
